package db

import (
	"time"

	"github.com/pkg/errors"
)

const (
	tableNameMessage = "message"
	fieldNameTopicId = "topic_id"
)

type Message struct {
	ProjectId           string    `orm:"column(project_id);size(64);pk" json:"project_id"`
	Name                string    `orm:"column(name);size(256)" json:"name"`
	TopicUrn            string    `orm:"column(topic_urn);size(512)" json:"topic_urn"`
	DisplayName         string    `orm:"column(display_name);size(192)" json:"display_name"`
	StateAndReason      string    `orm:"column(state_and_reason);size(1024)" json:"state_and_reason"`
	EnterpriseProjectId string    `orm:"column(enterprise_project_id);size(64)" json:"enterprise_project_id"`
	NoticeTraceStatus   string    `orm:"column(notice_trace_status);size(64)" json:"notice_trace_status"`
	CreationTime        time.Time `orm:"column(creation_time);type(datetime);auto_now_add" json:"record_time"`
}

type MessageTableOpt struct {
}

func GetMessageTableOpt() *MessageTableOpt {
	return &MessageTableOpt{}
}

func (m *MessageTableOpt) Insert(message *Message) error {
	_, err := ormer.Insert(message)
	if err != nil {
		return errors.Wrapf(err, "insert message config err topic urn[%s]", message.TopicUrn)
	}
	return nil
}

func (m *MessageTableOpt) Update(message *Message) error {
	_, err := ormer.Update(message)
	if err != nil {
		return errors.Wrapf(err, "update message err, topic urn %s", message.TopicUrn)
	}
	return nil
}

func (m *MessageTableOpt) Delete(projectId string) error {
	message, err := m.Show(projectId)
	if err != nil {
		return errors.Wrapf(err, "query message err")
	}
	_, err = ormer.Delete(message)
	if err != nil {
		return errors.Wrapf(err, "delete message err, topic id [%s]", message.TopicUrn)
	}
	return nil
}

func (m *MessageTableOpt) Show(projectId string) (*Message, error) {
	var message Message
	err := ormer.QueryTable(tableNameMessage).Filter(fieldNameProjectId, projectId).One(&message)
	return &message, err
}
